<template>
    <a-modal
      :bodyStyle="bodyStyle"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="() => { $emit('cancel') }"
    >
      <a-form layout='vertical' :form="form">
        <a-form-item  :class="{'a-form-item':true}" v-bind="formItemLayout" label="版本号">
          <a-tree-select
            :treeData="treeData"
            :value="classifyIds"
            @change="onChange"
            treeCheckable
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :showCheckedStrategy="SHOW_PARENT"
            searchPlaceholder="Please select"
          />
        </a-form-item>
         <!-- <a-form-item class="a-form-item" v-bind="formItemLayout" label="期号">
          <a-input
            v-decorator="[
              'issueNumber',
              {
                rules: [{ required: true, message: '请输入期号!' }],
              }
            ]"
            placeholder="请输入期号"
          />
        </a-form-item> -->
        <a-form-item :class="{'a-form-item':true}" v-bind="formItemLayout" label="图片链接">
          <a-input
            v-decorator="[
              'link',
              {
                rules: [{ required: true, message: '请输入图片链接!' }],
              }
            ]"
            placeholder="请输入图片链接"
          />
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="来源">
          <a-select
            v-decorator="[
              'source',
              {
                rules: [{ required: true, message: '请选择来源!' }],
              }
            ]"
            placeholder="请选择来源">
            <a-select-option :value="item.dataValue" v-for="item in sources" :key="item.id">{{item.dataName}}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item class="a-form-item" v-bind="formItemLayout" label="产品类型">
          <a-select
            v-decorator="[
              'productType',
              {
                rules: [{ required: true, message: '请选择产品类型!' }],
              }
            ]"
            placeholder="请选择产品类型">
            <a-select-option :value="item.dataValue" v-for="item in productTypes" :key="item.id">{{item.dataName}}</a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="下载金额">
          <a-input-number
            :min="0"
            :precision="2"
            v-decorator="[
              'amount',
              {
                rules: [{ required: true, message: '请输入下载金额!' }],
              }
            ]"
            placeholder="下载金额"
          />
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="标签">
          <a-input
            v-decorator="[
              'tag',
              {
                rules: [{ required: false, message: '请输入标签!' }],
              }
            ]"
            placeholder="请输入标签"
          />
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="上传图片">
          <a-radio-group @change="onChangeUploadMethod" defaultValue="2">
            <a-radio-button value="1">本地上传</a-radio-button>
            <a-radio-button value="2">网址上传</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="效果图网址" v-show="urlUpload">
          <a-input
            v-decorator="[
              'photoImageUrl',
              {
                rules: [{ required: false, message: '请输入效果图网址!' }],
              }
            ]"
            placeholder="请输入效果图网址"
          />
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="款式图网址" v-show="urlUpload">
          <a-row type="flex" v-for="(item, index) in modelUrls" :key="index" class="model-url-row">
            <a-col :span="20" :order="1">
              <a-input
                @change="changeModel"
                :data-index = "index"
                v-decorator="[
                  `modelUrl${index + 1}`,
                  {
                    rules: [{ required: false, message: '请输入款式图网址!' }],
                  }
                ]"
                placeholder="请输入效果图网址"
              />
            </a-col>
            <a-col :span="2" :order="2" class="center-center">
              <a-avatar shape="square" :src="item" icon="user" />
            </a-col>
            <a-col :span="2" :order="3" class="center-center">
              <a-icon type="plus-circle" @click="addModel" v-if="index===0"/>
              <a-icon type="minus-circle" @click="delModel(index)" v-else />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item class="a-form-item" v-show="localUpload">
          <a-row type="flex">
            <a-col :span="6" :order="1">
              <a-upload
                  listType="picture-card"
                  :showUploadList="false"
                  :beforeUpload="beforeUpload"
                  v-decorator="['photoImage',{}]"
                >
                  <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
                  <div v-else>
                      <a-icon :type="loading ? 'loading' : 'plus'" />
                      <div class="ant-upload-text">效果图</div>
                  </div>
                </a-upload>
            </a-col>
            <a-col :span="18" :order="2">
              <a-upload
                  listType="picture-card"
                  :fileList="modelList"
                  :beforeUpload="beforeUploadModel"
                  @preview="handlePreview"
                  @change="handleChange"
                >
                  <div v-if="modelList.length < 4">
                    <a-icon type="plus" />
                    <div class="ant-upload-text">款式图</div>
                  </div>
                </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item class="a-form-item">
          <div v-for="item in similarImages" :key="item.id" class="similar-image-item" @click="handlePreview({url:item.url})">
            <img :src="item.url"/>
          </div>
        </a-form-item>
        <a-form-item class="a-form-item">
          <a-input type="hidden" v-decorator="['id', {}]"/>
        </a-form-item>
      </a-form>
    </a-modal>
</template>
<script>
import Vue from 'vue'
import api from '@/core/Api'
import serv from './ChartFindingRecordService'
// import imageSearch from '../image-store/ImageSearchService'
import { TreeSelect, InputNumber, Radio } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
Vue.component(InputNumber.name, InputNumber)
Vue.component(Radio.Group.name, Radio.Group)
Vue.component(Radio.Button.name, Radio.Button)
export default {
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {
    // this.productTypes = this.dictionary().PRODUCT_TYPE
    this.sources = this.dictionary().IMAGE_SOURCE
  },
  data () {
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      bodyStyle: { height: 400 },
      // productTypes: [],
      sources: [],
      loading: false,
      imageUrl: '',

      treeData: [],
      classifyIds: [],
      SHOW_PARENT,

      previewVisible: false,
      previewImage: '',
      modelList: [],

      similarImages: [],
      modelUrls: [''],
      uploadMethod: '2'
    }
  },
  computed: {
    localUpload: function () {
      return this.uploadMethod === '1'
    },
    urlUpload: function () {
      return this.uploadMethod === '2'
    }
  },
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    confirmLoading: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    visible: function (nvalue) {
      !nvalue || this.getTree()
      if (nvalue && Object.keys(this.data).length > 0) {
        setTimeout(() => {
          this.form.setFieldsValue(this.data)
        }, 10)
        this.changeUploadMethod()
        if (this.data.id) this.getChartFindingAndClassifyList(this.data.id)
      } else {
        this.imageUrl = ''
        this.classifyIds = []
        this.modelList = []
        this.modelUrls = ['']
        this.uploadMethod = '2'
      }
      this.similarImages = []
    }
  },
  methods: {
    handleOk (e) {
      let files = {}
      for (let [index, elem] of this.modelList.entries()) {
        if (elem.originFileObj) {
          files[`modelFile${index + 1}`] = elem.originFileObj
        } else {
          files[`model${index + 1}`] = elem.url
        }
      }
      this.$emit('ok', files, this.classifyIds)
    },
    handleCancel () {
      this.previewVisible = false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
        return false
      }
      const r = isJPG && isLt2M
      if (r) {
        this.similarImageByChartFinding({file})
        api.getBase64(file, (imageUrl) => {
          this.imageUrl = imageUrl
          const name = this.$api.getName(file.name)
          // let {groups: {one, two}} = /^(?<one>.+)[＿_]?(?<two>.*)$/u.exec(api.getName(file.name))
          let index = name.indexOf('_')
          if (index === -1) {
            index = name.indexOf('＿')
          }
          let d = {}
          if (index > -1) {
            Object.assign(d, {
              name: name.substring(0, index),
              tag: name.substring(index + 1)
            }, this.data)
          } else {
            Object.assign(d, { name: name }, this.data)
          }
          console.log(d)
          this.form.setFieldsValue(d)
          this.loading = false
        })
      }
      return false
    },
    beforeUploadModel (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
        return false
      }
      const r = isJPG && isLt2M
      if (r) {
        this.similarImageByChartFinding({file})
        return false
      }
      return false
    },
    handleChange ({ fileList }) {
      console.log(fileList)
      let list = []
      for (let file of fileList) {
        if (file.originFileObj) {
          api.getBase64(file.originFileObj, (imageUrl) => {
            list.push({
              uid: file.uid,
              name: file.name,
              status: 'done',
              url: imageUrl,
              originFileObj: file.originFileObj
            })
          })
        } else {
          list.push(file)
        }
      }
      this.modelList = list
    },
    onChangeUrl (e) {
      console.log(11212)
    },
    onChangeCopyright (e) {
      this.copyright = e.target.checked
    },
    onChangeDisabled (e) {
      this.disabled = e.target.checked
    },
    onChange (value) {
      this.classifyIds = value
    },
    async getTree () {
      this.treeData = await serv.getTree()
    },
    async getChartFindingAndClassifyList (id) {
      const ids = []
      for (let item of await serv.getChartFindingAndClassifyList(id)) {
        console.log(item)
        ids.push(item.imageStorageClassifyId)
      }
      this.classifyIds = ids
    },
    async similarImageByChartFinding ({file, fileUrl}) {
      // let res1 = await imageSearch.getPage({
      //   file: file,
      //   page: 1,
      //   size: 4
      // })
      const similarImages = []
      // for (let item of res1.content) {
      //   similarImages.push(item)
      // }

      let formData = new FormData()
      if (file) formData.append('file', file)
      if (fileUrl) formData.append('fileUrl', fileUrl)
      formData.append('page', 1)
      formData.append('size', 4)
      let res = await serv.similarImageByChartFinding(formData)
      for (let item of res) {
        similarImages.push({
          id: item.cont_sign,
          ...JSON.parse(item.brief)
        })
      }
      this.similarImages = similarImages
    },
    changeModel (e) {
      console.log(e)
      this.similarImageByChartFinding({fileUrl: e.target.value})
      setTimeout(() => {
        let urls = []
        for (let index = 0; index < this.modelUrls.length; index++) {
          urls.push(this.form.getFieldValue(`modelUrl${index + 1}`))
        }
        this.modelUrls = urls
      }, 10)
    },
    addModel () {
      if (this.modelUrls.length < 4) {
        this.modelUrls = [...this.modelUrls, '']
      }
    },
    delModel (num) {
      let urls = []
      for (let index = 0; index < this.modelUrls.length; index++) {
        if (index < num) {
          urls.push(this.form.getFieldValue(`modelUrl${index + 1}`))
        } else if (index > num) {
          let value = this.form.getFieldValue(`modelUrl${index + 1}`)
          urls.push(value)
          let v = {}
          v[`modelUrl${index}`] = value
          this.form.setFieldsValue(v)
        }
      }
      this.modelUrls = urls
    },
    onChangeUploadMethod (e) {
      this.uploadMethod = e.target.value
      this.changeUploadMethod()
    },
    changeUploadMethod () {
      if (this.uploadMethod === '1') {
        let fields = ['photoImageUrl']
        for (let i = 1; i < 5; i++) {
          if (this.data[`model${i}`]) {
            this.modelList.push({
              uid: `${this.data.id}${i}`,
              name: this.data.name,
              status: 'done',
              url: this.data[`model${i}`]
            })
          }
          fields.push(`modelUrl${i}`)
        }
        this.imageUrl = this.data.url
        this.modelUrls = ['']
        this.form.resetFields(fields)
      } else {
        this.imageUrl = null
        this.modelList = []
        let urls = []
        let fields = {photoImageUrl: this.data.url}
        for (let i = 1; i < 5; i++) {
          let modelurl = this.data[`model${i}`]
          if (modelurl) {
            urls.push(modelurl)
            fields[`modelUrl${i}`] = modelurl
          }
        }
        this.modelUrls = urls.length === 0 ? [''] : urls
        setTimeout(() => {
          this.form.setFieldsValue(fields)
        }, 10)
      }
    }
  }
}
</script>

<style scoped>
img {
  max-width: 100%;
}
.a-form-item {
  margin-bottom: 0px;
}
.similar-image-item {
  float: left;
  max-width: 100px;
  max-height: 100px;
  min-height: 100px;
  margin: 5px;
}
.similar-image-item img{
  max-width: 100%;
  max-height: 100%;
}
.model-url-row {
  margin-bottom: 8px;
}
</style>
